﻿#light

namespace Langexplr.SwfSupport

open System.IO
open System
open Langexplr.SwfSupport
open Langexplr.SwfSupport.Utils

type SwfFile(fileVersion : byte,fileLength:int,rect : int*int*int*int,bitRate :int16,frameCount:int16,tags : SwfTag list) = class
  
  member this.Tags 
    with get() = tags

  static member collectTags(bustream:BinaryReader) = 
      let tagHeader = bustream.ReadInt16() in
      let tagType = (tagHeader >>> 6) in
      let tagSize = tagHeader &&& int16(0x3f) in
      if tagType <> int16(0) then
         let content = if tagSize = int16(0x3f) then
                           let longTagSize = bustream.ReadInt32() in
                           bustream.ReadBytes(longTagSize)                         
                        else         
                           if tagSize <> int16(0) then bustream.ReadBytes(int(tagSize)) else [||] in
                           
         (tagType,content)::(SwfFile.collectTags(bustream))
      else
         []


  static member ReadFrom( inputStream : Stream, compressedStreamCreator : Stream -> BinaryReader ) =
    let reader = new BinaryReader(inputStream) in
    let str = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(3)) in 
    let fileVersion = reader.ReadByte() in
    let fileLength = reader.ReadInt32() in
    let contentReader = 
         if str = "CWS" then 
            compressedStreamCreator(inputStream) 
         else 
            reader in
    let rect = ReadRect(contentReader) in        
    let bitRate = contentReader.ReadInt16() in
    let frameCount = contentReader.ReadInt16() in
    let solver = TagSolver() in
    let tags = List.map 
                  (fun (tagNumber,content) -> 
                     let tagReader = solver.SolveReaderForTag(int(tagNumber)) in
                        tagReader(content))
                  <| SwfFile.collectTags(contentReader)
    
    SwfFile(fileVersion, fileLength, rect, bitRate, frameCount, tags)
   

    
end
